import React, { Component } from 'react';
import {
	View, Text, StyleSheet, TouchableOpacity, Image, DeviceEventEmitter, TextInput, ScrollView,
	PixelRatio, ActivityIndicator
} from 'react-native';
import { GLOBAL } from '../../../config/global';
import { style } from '../../../theme/style';
import { Common } from '../../../component/common/Common.js';
import { enterpriseStyles } from '../_common/enterpriseStyle';
import { InputRow, LargeBtn } from '../../requirement-plan/component/Component.js';
import ModalAreaComponent from '../../../component/ModalAreaComponent.js';
import ToastUtil from '../../../utils/toast';
import Dictionary from '../../../utils/dictionary';

const scale = GLOBAL.SCALE;

const arrowLeft = require('../../../imgs/arrow-left.png');
let sendDataChange = {};

export class AddressAddPage extends Component {

	static navigationOptions = ({ navigation }) => {
		const companyAddress = navigation.state.params.companyAddress;
		sendDataChange = companyAddress;

		return {
			headerTitle: '地址信息',
			headerLeft: <Common type="headLeft" onPress={() => {
				navigation.state.params.setParamsVo(navigation);
			}} />,
			headerTintColor: style.color.dark,
			headerStyle: style.headTow.headerStyleWidthBorder,
			headerTitleStyle: style.headTow.headerTitleStyle,
		};
	};

	constructor(props) {
		super(props);
		this.state = {
			addressTypeList: [], // 地址类型
			addressType: '', // 默认选择库区
			addressTypeValue: '',
			selectIndex: 0,
			showSelect: false,

			modalAreaVisible: false,
			areaText: '请选择',
			areaModalProp: {
				addressInfo: null,
			}
		}

		this._didPressLargeBtn = this._didPressLargeBtn.bind(this);
		this.goBack = this.props.navigation.state.params.goBack;
		this.sendData = this.props.navigation.state.params.companyAddress;
		if (this.sendData) {
			this.areaText = (this.sendData.provinceName + this.sendData.cityName + this.sendData.areaName) || '请选择';
			this.setState({
				areaText: this.areaText
			})
		}

		if (sendDataChange.detailAddress) {
			this.sendDataChange = {};
			this.sendDataChange.areaCode = sendDataChange.areaCode;
			this.sendDataChange.checked = sendDataChange.checked;
			this.sendDataChange.cityCode = sendDataChange.cityCode;
			this.sendDataChange.detailAddress = sendDataChange.detailAddress;
			this.sendDataChange.addressName = sendDataChange.addressName;
			this.sendDataChange.provinceCode = sendDataChange.provinceCode;
			this.sendDataChange.provinceName = sendDataChange.provinceName;
			this.sendDataChange.cityName = sendDataChange.cityName;
			this.sendDataChange.areaName = sendDataChange.areaName;
			this.sendDataChange.index = sendDataChange.index;
			if (sendDataChange.companyId) {
				this.sendDataChange.companyId = sendDataChange.companyId;
			}
		} else {
			this.sendDataChange = null;
		}
	}

	render () {
		const { detailAddress, addressName } = this.sendData;
		const { modalAreaVisible, areaModalProp, loaded, addressTypeList, addressType, showSelect, addressTypeValue, selectIndex } = this.state;
		return (
			<View style={[styles.container]}>
				<TouchableOpacity activeOpacity={1} style={styles.selectWrap} onPress={() => { this.toggleSelect() }}>
					<Text style={styles.selectText}>{addressTypeValue}</Text>
					<Image style={styles.selectImg} source={require('../../../imgs/global/down.png')} />
				</TouchableOpacity>

				<ScrollView style={styles.scrollView} keyboardShouldPersistTaps={'handled'} keyboardDismissMode={'on-drag'}>
					<View style={styles.wrap}>
						<View style={{ width: 345 * scale, }}>
							<InputRow text={addressType == '1' ? '仓库名称' : '片区名称'}>
								<View style={styles.inputRowRight}>
									<TextInput
										ref="addressName"
										style={styles.textInput}
										underlineColorAndroid='transparent'
										placeholder={"请输入"}
										placeholderTextColor="#999"
										maxLength={30}
										editable={true}
										defaultValue={addressName}
										onChangeText={(addressName) => {
											this.sendData.addressName = addressName;
										}}
									/>
								</View>
							</InputRow>

							{
								addressType == '1' ?
									(<InputRow text={'地区'}>
										<TouchableOpacity style={styles.inputRowRight} activeOpacity={.5} onPress={() => {
											this.setState({
												modalAreaVisible: true
											});
										}}>
											<Text style={enterpriseStyles.text}>{this.areaText}</Text>
											<Image source={arrowLeft} style={enterpriseStyles.arrowLeft} />
										</TouchableOpacity>
									</InputRow>) : null
							}

							{
								addressType == '1' ?
									(<InputRow text={'详细地址'}>
										<View style={styles.inputRowRight}>
											<TextInput
												ref="detailAddress"
												style={styles.textInput}
												underlineColorAndroid='transparent'
												returnKeyType='done'
												keyboardType='default'
												placeholder={"请输入"}
												placeholderTextColor="#999"
												maxLength={30}
												editable={true}
												defaultValue={detailAddress}
												onChangeText={(detailAddress) => {
													this.sendData.detailAddress = detailAddress;
												}}
											/>
										</View>
									</InputRow>) : null
							}
						</View>
					</View>
				</ScrollView >
				<LargeBtn onPress={this._didPressLargeBtn} text={'保存并使用'} />
				{areaModalProp.addressInfo ? <ModalAreaComponent {...areaModalProp} selectCustom={true} visible={modalAreaVisible} /> : null}
				{loaded ?
					<View style={styles.loadBox}>
						<View style={styles.loadedCell}>
							<ActivityIndicator
								animating={true}
								color={'#fff'}
								size="small"
							/>
						</View>
					</View> : null}
				{showSelect ? (<Common data={addressTypeList} itemFn={this.changeAddressType} imgIndex={selectIndex} allClick={this.toggleSelect} styleOut={{ marginTop: 40 * scale }} type="selectModal" />) : null}
			</View>

		)
	}

	async componentWillMount () {
		this.props.navigation.setParams({
			setParamsVo: this.setParamsVo,
			sendDataChange: this.sendDataChange,
		})
		await this.getDictionary();
		this._getAddressInfo();
	}

	async getDictionary () {
		let addressTypeList = await Dictionary.get('EC_ADDRESS_TYPE');
		let selectIndex;
		let addressType;
		let addressTypeValue;

		if (addressTypeList && addressTypeList.length > 0) {
			addressTypeList.map((item, index) => {
				item.title = item.dictName
				if (this.sendData && this.sendData.addressType && this.sendData.addressType == item.dictKey) {
					selectIndex = index;
					addressType = item.dictKey;
					addressTypeValue = item.dictName;
				}
			})
			this.setState({
				addressTypeList,
				addressType: addressType || addressTypeList[0].dictKey,
				addressTypeValue: addressTypeValue || addressTypeList[0].dictName,
				selectIndex: selectIndex || 0
			}, () => {
				this.sendData.addressType = addressType || addressTypeList[0].dictKey;
			})
		}
	}

	setParamsVo (navigation) {
		navigation.state.params.bankVoBack = true;
		const { navigate } = navigation;
		navigate(navigation.state.params.goBack);
	}

	componentWillUnmount () {
		const { detailAddress, areaCode, addressName } = this.sendData;
		const sendData = this.props.navigation.state.params.bankVoBack ? this.sendDataChange : this.sendData;
		if (addressName) {
			DeviceEventEmitter.emit('addressParamTwo', { addressList: sendData ? [sendData] : null });
		}
		this.setState({
			modalAreaVisible: false
		});
	}

	/**
	 * 获取省市区
	 */
	async _getAddressInfo () {
		let mapData = require('../../../data/map.json');
		this.setState({
			areaModalProp: {
				addressInfo: mapData.data,
				cancelPress: () => {
					this.setState({
						modalAreaVisible: false
					});
				},
				confirmPress: (data) => {
					const { province, city, area } = data;

					this.areaText = `${province.areaName}${city.areaName ? ('，' + city.areaName) : ''}${area.areaName ? ('，' + area.areaName) : ''}`;

					this.sendData.provinceCode = province.areaId || '';
					this.sendData.cityCode = city.areaId || '';
					this.sendData.areaCode = area.areaId || '';
					this.sendData.provinceName = province.areaName || '';
					this.sendData.cityName = city.areaName || '';
					this.sendData.areaName = area.areaName || '';

					this.setState({
						modalAreaVisible: false,
						areaText: this.areaText
					});
				},
			},
			loaded: false
		})
	}

	/**
 * 点击底部按钮
 */
	async _didPressLargeBtn () {
		const { provinceCode, addressName, addressType } = this.sendData;
		if (addressType == '1') {
			if (!addressName) {
				ToastUtil.showWarning('请输入仓库名称');
				return;
			}
			if (!provinceCode) {
				ToastUtil.showWarning('请选择地区');
				return;
			}
		} else {
			if (!addressName) {
				ToastUtil.showWarning('请输入片区名称');
				return;
			}
			this.sendData.provinceCode = this.sendData.cityCode = this.sendData.areaCode = '';
			this.sendData.provinceName = this.sendData.cityName = this.sendData.areaName = '';
			this.sendData.detailAddress = '';
		}
		console.log('this.sendData', this.sendData)
		const { navigate } = this.props.navigation;
		if (this.goBack == 'EnterpriseCreateAdditionInfo') {
			this.sendData.checked = true;
		}
		navigate(this.goBack, {
			addressList: [this.sendData],
		});

	}

	changeAddressType = (res) => {
		if (res) {
			this.setState({
				addressType: res.item.dictKey,
				addressTypeValue: res.item.dictName,
				selectIndex: res.index
			}, () => {
				this.sendData.addressType = res.item.dictKey;
				this.toggleSelect()
			})
		}
	}

	toggleSelect = () => {
		this.setState({
			showSelect: !this.state.showSelect
		})
	}
}

const styles = StyleSheet.create({
	text: {
		fontSize: 14 * scale,
		color: '#4B4B4B'
	},
	textInput: {
		borderWidth: 0,
		fontSize: 13 * scale,
		color: '#404040',
		width: '100%',
		height: 42 * scale,
		padding: 0,
		alignSelf: 'center',
	},
	scrollView: {
		flex: 1,
	},
	container: {
		flex: 1,
		backgroundColor: '#F5F5F5',
	},
	wrap: {
		backgroundColor: '#fff',
		alignItems: 'center',
	},
	inputRowRight: {
		flex: 1,
		flexDirection: 'row',
		alignItems: 'center',
		justifyContent: 'space-between',
		flexWrap: 'wrap',
	},
	loadBox: {
		height: '100%',
		width: '100%',
		position: 'absolute',
		top: 0,
		borderTopColor: '#e4e4e4',
		borderTopWidth: 1 / PixelRatio.get(),
		backgroundColor: 'rgba(255, 255, 255,0.1)',
	},
	loadedCell: {
		position: 'absolute',
		left: 150 * scale,
		top: 150 * scale,
		width: 75 * scale,
		height: 75 * scale,
		backgroundColor: 'rgba(0, 0, 0, .5)',
		borderRadius: 7,
		justifyContent: 'center',
		alignItems: 'center',
	},
	selectWrap: {
		height: 40 * scale,
		marginBottom: 12 * scale,
		backgroundColor: '#fff',
		flexDirection: 'row',
		alignItems: 'center',
		justifyContent: 'center'
	},
	selectText: {
		color: '#4B4B4B'
	},
	selectImg: {
		width: 8 * scale,
		height: 4 * scale,
		marginLeft: 3 * scale
	}
})